package com.hoyin.viewtest;
/**
 * Author by Hoyin,
 * Email ,
 * Date on 2021/4/30.
 */
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toolbar;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class ToolbarActivity extends AppCompatActivity {
	private final int TOOLBAR_OPTIONS_COUNT = 3;                //toolbar的选项数量
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_toolbar);
		Toolbar toolbar = findViewById(R.id.toolbar);
		ArrayList<View> toolbarOptions = new ArrayList<>();     //构造toolbar.addChildrenForAccessibility()所需的参数
		for (int i = 0; i < TOOLBAR_OPTIONS_COUNT; i++) {
			toolbarOptions.add(new TextView(this));     //通过（反）注释来预览Button和TextView的不同效果
			//toolbarOptions.add(new Button(this));
		}
		toolbar.post(() -> initializeToolBar(toolbar, toolbarOptions)); //view.post将runnable在队列中发布
	}

	private void initializeToolBar(Toolbar toolbar, ArrayList<View> toolbarOptions) {
		if (toolbarOptions.isEmpty()) return;
		Object genericClass = toolbarOptions.get(0).getClass();
		int toolbarWidth = toolbar.getWidth();
		int toolbarHeight = toolbar.getHeight();
		//按options所属类进行设置和添加
		if (genericClass.equals(Button.class)) {
			for (int i = 0; i < toolbarOptions.size(); i++) {
				Button toolbarOption = (Button) toolbarOptions.get(i);
				toolbarOption.setText("Option" + i);
				toolbarOption.setWidth(toolbarWidth / TOOLBAR_OPTIONS_COUNT);
				toolbarOption.setHeight(toolbarHeight);
				toolbarOption.setAllCaps(false);
				toolbar.addView(toolbarOption);
			}
		} else if (genericClass.equals(TextView.class)) {
			for (int i = 0; i < toolbarOptions.size(); i++) {
				TextView toolbarOption = (TextView) toolbarOptions.get(i);
				toolbarOption.setText("Option" + i);
				toolbarOption.setWidth(toolbarWidth / TOOLBAR_OPTIONS_COUNT);
				toolbarOption.setHeight(toolbarHeight);
				toolbarOption.setGravity(Gravity.CENTER);
				toolbarOption.setBackgroundColor(Color.rgb(i * 25 + 55, i * 50 + 55, i * 100 + 55));
				toolbar.addView(toolbarOption);
			}
		}
		toolbar.addChildrenForAccessibility(toolbarOptions);        //向toolbar添加控件
	}


}